package com.aurora.azurstarter

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Environment
import androidx.core.app.ActivityCompat
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.Logger
import java.lang.Exception
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import kotlin.system.exitProcess

@SuppressLint("SetTextI18n")
class MainActivity : AppCompatActivity() {

    var counter : TimerCountDown? = null
    var fullPath = ""

    inner class TimerCountDown(millisInFuture: Long) : CountDownTimer(millisInFuture, 1000) {

        override fun onTick(p0: Long) {
            this@MainActivity.infoLabel.text = "等待 ${p0 / 1000} 秒..."
        }

        override fun onFinish() {
            this@MainActivity.infoLabel.text = "启动“碧蓝航线”特别版..."

            val intent = Intent()
            intent.setClassName("com.bilibili.azurlane", "com.manjuu.azurlane.MainActivity")
            intent.action = "android.intent.action.MAIN"
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
            Thread.sleep(500)
            exitProcess(0)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        Logger.addLogAdapter(AndroidLogAdapter())

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val sdcardPath = Environment.getExternalStorageDirectory().path
        fullPath = "$sdcardPath/Android/data/com.bilibili.azurlane/files/localization.txt"

        try {
            val f = File(fullPath)
            val exists = f.isFile
            RootUtils.instance().su("rm -f $fullPath")
            val exists2 = f.isFile
            Logger.i("Delete file $fullPath by 'su', isFile:$exists, after delete isFile:$exists2.")

            prepareGame()
        } catch (e: Exception) {
            this.infoLabel.text = "错误：未能获取 Root 权限！"
            if(verifyStoragePermission())
                _doDeleteFileAndStartGame()
        }
    }

    private fun prepareGame() {
        infoLabel.text = "已获取 ROOT 权限，准备启动游戏..."

        counter = TimerCountDown(3000)
        counter?.start()
    }

    private fun _doDeleteFileAndStartGame() {
        val f = File(fullPath)
        val exists = f.isFile
        f.delete()
        val exists2 = f.isFile
        Logger.i("Delete file $fullPath by 'File.delete', isFile:$exists, after delete isFile:$exists2.")
        prepareGame()
    }

    private fun verifyStoragePermission() : Boolean {
        try {
            val permission = ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE")
            if(permission == PackageManager.PERMISSION_GRANTED)
                return true
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE)
        } catch (ex: Exception) {
            this.infoLabel.text = "错误：${ex.message}"
        }
        return false
    }

    companion object {
        const val REQUEST_EXTERNAL_STORAGE:Int = 1
        val PERMISSIONS_STORAGE = arrayOf(
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" )
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if(requestCode != REQUEST_EXTERNAL_STORAGE)
            return

        if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            _doDeleteFileAndStartGame()
        } else {
            this.infoLabel.text = "未能获取 ROOT 或者读写权限！"
        }
    }

}